/*
 * Copyright (C) 2012 Le Tuan Anh <anh.takaji@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ezcms.dal.hibernate.mysql;

import ezcms.constants.AuthenticationStatus;
import ezcms.dal.UserDAO;
import ezcms.dto.User;
import ezcms.exceptions.DataLayerException;
import java.util.List;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Le Tuan Anh <anh.takaji@gmail.com>
 */
public class UserDAOImpl implements UserDAO {

    @Override
    public User getUser(String email) throws DataLayerException {
        Object result = HibernateUtil.getObjectByConditions(User.class, Restrictions.eq("email", email), "Cannot select user with id = " + email);
        return (result == null) ? null : (User) result;
    }

    @Override
    public void saveUser(User user) throws DataLayerException {
        HibernateUtil.saveObject(user, "Cannot save given user");
    }

    @Override
    public void deleteUser(User user) throws DataLayerException {
        HibernateUtil.deleteObject(user);
    }

    @Override
    public List<User> getAllUsers() throws DataLayerException {
        return HibernateUtil.getListByConditions(User.class, null, "Cannot retrieve all users");
    }

    @Override
    public int authenticate(User user) throws DataLayerException {
        Criterion conditions = Restrictions.and(
                Restrictions.eq("email", user.getEmail()), Restrictions.eq("password", user.getPassword()));
        Object result = HibernateUtil.getObjectByConditions(User.class, conditions, "Cannot authenticate user = " + user);
        if (result == null) {
            //TODO: Want to know details problem? Invalid user? Invalid password? Add more here
            return AuthenticationStatus.INVALID;
        } else {
            return AuthenticationStatus.VALID_USER;
        }
    }
}
